package utils
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.FocusEvent;
	import flash.events.KeyboardEvent;
	import flash.events.MouseEvent;
	import flash.text.TextFieldType;
	import flash.ui.Keyboard;
	
	import net.flashpunk.utils.Key;

	public class LabelInput extends Label
	{
		public static const CHANGE_EVENT:String = "changeEvent";
		
		protected var _oldText:String;
		private var _selected:Boolean;
		
		public function LabelInput(text:String)
		{
			super(text);
			_oldText = text;
			_textField.selectable = true;
			_textField.backgroundColor = 0xFFFEA6;
			addEventListener(MouseEvent.CLICK, mouseClick);
			addEventListener(MouseEvent.MOUSE_OVER, mouseOver);
			addEventListener(MouseEvent.MOUSE_OUT, mouseOut);
		}
		
		protected function mouseClick(event:MouseEvent):void
		{
			_oldText = _textField.text;
			_selected = true;
			
			removeEventListener(MouseEvent.CLICK, mouseClick);
			TopLevel.stage.addEventListener(KeyboardEvent.KEY_DOWN, enterPress);
			addEventListener(FocusEvent.FOCUS_OUT, lostFocus);
			
			_textField.type = TextFieldType.INPUT;
			_textField.setSelection(0, _textField.length);
			_textField.background = true;
			
		}
		
		protected function enterPress(event:KeyboardEvent):void
		{
			if (event.keyCode == Keyboard.ENTER)
			{
				_selected = false;
				addEventListener(MouseEvent.CLICK, mouseClick);
				TopLevel.stage.removeEventListener(KeyboardEvent.KEY_DOWN, enterPress);
				removeEventListener(FocusEvent.FOCUS_OUT, lostFocus);
			
				dispatchEvent(new Event(LabelInput.CHANGE_EVENT));
				_textField.background = false;
			}
		}
		
		protected function lostFocus(event:FocusEvent):void
		{
			_selected = false;
			addEventListener(MouseEvent.CLICK, mouseClick);
			TopLevel.stage.removeEventListener(KeyboardEvent.KEY_DOWN, enterPress);
			removeEventListener(FocusEvent.FOCUS_OUT, lostFocus);
			
			_textField.background = false;
			_textField.text = _oldText;
		}
		
		protected function mouseOver(event:MouseEvent):void
		{
			_textField.background = true;		
		}
		
		protected function mouseOut(event:MouseEvent):void
		{
			if (!_selected)
			{
				_textField.background = false;		
			}
		}
	}
}